package com.zbj.validator.util;

import com.zbj.validator.common.Result;
import com.zbj.validator.common.Results;
import org.springframework.util.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;

/**
 * 参数验证
 * @author weigang
 * @create 2017-04-12
 **/
public class ValidationUtil {

    private static ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    private static Validator validator = factory.getValidator();

    public static <E> Result<String> validate(E obj) {
        if (obj instanceof Collection) {
            Collection collection = (Collection) obj;
            for (Iterator iterator = collection.iterator(); iterator.hasNext();) {
                Object item = iterator.next();
                Result<String> res = validateObject(item);
                if (!res.isSuccess()) {
                    return res;
                }
            }
            return Results.success();
        }
        return validateObject(obj);
    }

    private static Result<String> validateObject(Object obj) {
        Set<ConstraintViolation<Object>> violations = validator.validate(obj);
        if (CollectionUtils.isEmpty(violations)) {
            return Results.success();
        }

        StringBuilder builder = new StringBuilder();
        for (ConstraintViolation<Object> violation : violations) {
            builder.append(violation.getPropertyPath()).append(":");
            builder.append(violation.getMessage()).append("; ");
        }
        String error = builder.toString().substring(Constant.ZERO, builder.toString().length() - Constant.TWO);
        return Results.fail(error);
    }
}
